/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.openbookformat.obffinder.filters;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
import javax.swing.SwingWorker;
import org.openide.util.Exceptions;
import org.openide.util.Lookup;

/**
 *
 * @author matamh0a
 */
public final class FiltersManager {
    public static final String FIND_KEY = "find";
    public static final String REPLACE_KEY = "replace";
    public static final String USE_REGEXP_KEY = "use_reg_exp";
    public static final String IGNORE_CASE_KEY = "ignore_case";
    public static final String USE_VARIABLE_KEY = "use_variable";
    public static final String APPLY_TO_ALL_KEY = "apply_to_all";
    public static final String IGNORE_NEW_LINE_KEY = "ignore_new_line";
    public static final String DESCRIPTION_KEY = "description";

    private static FiltersManager instance;

    public static FiltersManager getInstance() {
        if(instance == null)
            instance = new FiltersManager();
        return instance;
    }

    private ArrayList<Filter> filters;

    private FiltersManager() {
        filters = new ArrayList<Filter>();
        refresh();
    }

    public boolean exist(String filterName) {
        return (new File(System.getProperty("user.home")
                + File.separator + ".obf" 
                + File.separator + "filters"
                + File.separator + filterName + ".flt")).exists();
    }
    
    public void refresh() {
        //clear filters
        filters.clear();

        //Get filters from the lookup
        Collection<? extends Filter> collection =
                Lookup.getDefault().lookupAll(Filter.class);
        Iterator it = collection.iterator();
        while(it.hasNext())
            filters.add((Filter) it.next());
        for(int i = 0; i < filters.size(); i++) {
            System.out.println("Lookup[" + i + "] - " + filters.get(i));
        }

        //Get lookup form disk (Fixed Lookups);
        (new SwingWorker<ArrayList<Filter>, Void>() {

            @Override
            protected ArrayList<Filter> doInBackground() throws Exception {
                ArrayList<Filter> filters = new ArrayList<Filter>();
                File dir = new File(System.getProperty("user.home")
                        + File.separator + ".obf" + File.separator + "filters");

                File[] files = dir.listFiles();
                Properties prop = new Properties();
                for(int i = 0; i < files.length; i++) {
                    prop.load(new FileInputStream(files[i]));
                    filters.add(new FixedFilter(
                            files[i].getName().substring(0, files[i].getName().lastIndexOf(".")), 
                            prop.getProperty(FIND_KEY), 
                            prop.getProperty(REPLACE_KEY),
                            prop.getProperty(USE_REGEXP_KEY).equals("yes"), 
                            prop.getProperty(IGNORE_CASE_KEY).equals("yes"), 
                            prop.getProperty(USE_VARIABLE_KEY).equals("yes"), 
                            prop.getProperty(IGNORE_NEW_LINE_KEY).equals("yes"), 
                            prop.getProperty(APPLY_TO_ALL_KEY).equals("yes"),
                            prop.getProperty(DESCRIPTION_KEY)));
                    System.out.println("Files[" + i + "] - " + filters.get(i));
                }

                return filters;
            }

            @Override
            protected void done() {
                try {
                    Iterator it = get().iterator();
                    while(it.hasNext())
                        filters.add((Filter)it.next());
                } catch (InterruptedException ex) {
                    Exceptions.printStackTrace(ex);
                } catch (ExecutionException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
        }).execute();
    }

    public ArrayList<Filter> getFilters() {
        return filters;
    }

    public Iterator<Filter> filtersIterator() {
        return filters.iterator();
    }

    public void saveFilter(Filter filter) {
        try {
            Properties prop = new Properties();
            prop.put(FIND_KEY, filter.getFindText());
            prop.put(REPLACE_KEY, filter.getReplaceText());
            prop.put(USE_REGEXP_KEY, filter.isRegExp() ? "yes" : "no");
            prop.put(IGNORE_CASE_KEY, filter.isIgnoreCase() ? "yes" : "no");
            prop.put(USE_VARIABLE_KEY, filter.isUseVariables() ? "yes" : "no");
            prop.put(IGNORE_NEW_LINE_KEY, filter.isUseIgonreNewLine() ? "yes" : "no");
            prop.put(APPLY_TO_ALL_KEY, filter.isApplyToAll() ? "yes" : "no");
            prop.put(DESCRIPTION_KEY, filter.getDescription());
            prop.store(new FileOutputStream(System.getProperty("user.home")
                    + File.separator + ".obf" + File.separator + "filters"
                    + File.separator + filter.getName() + ".flt"), "Filter "
                    + "file generated by OBF");
            filters.add(filter);
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
}
